/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    
    // 链表翻转
    ListNode* reverseList(ListNode* head)
    {
        if(head == nullptr) return head;
        ListNode* newHead = nullptr, *cur = head, *next = head->next;
        while(cur)
        {
            cur->next = newHead;
            newHead = cur;
            cur = next;
            if(next)
                next = next->next;
        }
        return newHead;
    }

    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        // 先逆置两个链表
        head1 = reverseList(head1);
        head2 = reverseList(head2);
        ListNode* cur1 = head1, *cur2 = head2;
        ListNode* newhead = new ListNode(0);
        int plus = 0;
        while(cur1 || cur2 || plus > 0)
        {
            if(cur1)
            {
                plus += cur1->val;
                cur1 = cur1->next;
            }
            if(cur2)
            {
                plus += cur2->val;
                cur2 = cur2->next;
            }
            ListNode* cur = new ListNode(plus % 10);
            plus /= 10;
            ListNode* next = newhead->next;
            newhead->next = cur;    // 头插
            cur->next = next;
        }
        cur1 = newhead->next;
        delete newhead;
        return cur1;
    }
};